<template>
  <PageMain title="订单">
    <el-tabs v-model="searchParams.status" @tab-change="handleClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="服务中" name="serve"></el-tab-pane>
      <el-tab-pane label="待付款" name="pay"></el-tab-pane>
      <el-tab-pane label="待接单" name="wait"></el-tab-pane>
      <el-tab-pane label="已接单" name="get"></el-tab-pane>
      <el-tab-pane label="已完成" name="finish"></el-tab-pane>
      <el-tab-pane label="退款中" name="refund"></el-tab-pane>
      <el-tab-pane label="已取消" name="cancel"></el-tab-pane>
    </el-tabs>
    <el-form label-suffix="：" inline>
      <el-form-item label="下单开始时间">
        <el-date-picker
            v-model="searchParams.start_time"
            type="datetime"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下单结束时间">
        <el-date-picker
            v-model="searchParams.end_time"
            type="datetime"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model="searchParams.order_no" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="阿姨">
        <el-select style="width: 180px" filterable v-model="searchParams.staff_id">
          <el-option
              v-for="item in staffList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单用户">
        <el-select style="width: 180px" filterable v-model="searchParams.member_id">
          <el-option
              v-for="item in memberList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="table-box">
      <el-table :data="dataSource">
        <el-table-column label="订单来源" prop="member.source" fixed="left">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-tag v-if="scope.row.member.source === 'wx'" type="primary" >小程序</el-tag>
              <el-tag v-else-if="scope.row.member.source === 'wx_h5'" type="success" >公众号</el-tag>
              <el-tag v-else type="info" >未知</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="order_no" fixed="left" />
        <el-table-column label="状态" fixed="left">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-tag :type="scope.row.statusText.color" >{{ scope.row.statusText.value }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="地址" show-overflow-tooltip width="200">
          <template #default="scope">
            {{ scope.row.address.address }} {{ scope.row.address.code }}
          </template>
        </el-table-column>
        <el-table-column label="联系人" prop="address.nickname" />
        <el-table-column label="联系电话" prop="address.phone" />
        <el-table-column label="实付金额" prop="pay_amount">
          <template #default="scope">
            <span >{{ scope.row.pay_amount }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="车费" prop="travel_mode_fee">-->
<!--          <template #default="scope">-->
<!--            <span >{{ scope.row.travel_mode_fee }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="结算项目价" prop="staff_amount">
          <template #default="scope">
            <span >{{ scope.row.staff_amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结算比例" prop="staff_ratio">
          <template #default="scope">
            {{ scope.row.staff_ratio }}%
          </template>
        </el-table-column>

        <el-table-column label="结算总价" prop="staff_amount">
          <template #default="scope">
            <span style="color: red">{{ (parseFloat(scope.row.staff_amount) + parseFloat(scope.row.travel_mode_fee)).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="阿姨" prop="staff.nickname" />
        <el-table-column label="阿姨电话" prop="staff.phone" />
        <el-table-column label="预约时间" prop="start_time" width="120px"/>
        <el-table-column label="客户备注" prop="remark" />
        <el-table-column label="下单时间" prop="create_time" width="120px"/>
        <el-table-column label="支付时间" prop="pay_time" width="120px"/>
        <el-table-column label="服务开始时间" prop="serve_time" width="120px"/>
        <el-table-column label="服务结束时间" prop="serve_end_time" width="120px"/>
        <el-table-column label="服务时长" fixed="right" prop="end_serve_time" width="160px">
          <template #default="scope">
            <el-tag style="padding: 15px 8px;font-size: 24px;font-weight: bold" v-if="scope.row.end_serve_time && scope.row.end_serve_time.includes('-')" type="danger">{{ scope.row.end_serve_time }}</el-tag>
            <el-tag style="padding: 15px 8px;font-size: 24px;font-weight: bold"  v-if="scope.row.end_serve_time && !scope.row.end_serve_time.includes('-')" type="primary">{{ scope.row.end_serve_time }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="160px">
          <template #default="scope">
            <el-button type="text" @click="openDialog(scope.row)" v-if="scope.row.pay_status === 2">退款</el-button>
            <el-button type="text" @click="openDialog2(scope.row)" v-if="scope.row.pay_status === 2">取消退款</el-button>
            <el-button type="text" @click="openAssignDialog(scope.row)" v-if="scope.row.statusText.value === '待接单' && !scope.row.staff_id">分配阿姨</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="changeSize"
          @current-change="changePage"
      />
    </div>
    <el-dialog v-model="dialogValue" title="退款" width="500px">
      <el-form ref="formRef" :model="currentRow" :rules="rules">
        <el-form-item label="项目金额" prop="settlement_ratio">
         {{ currentRow.pay_amount - currentRow.travel_mode_fee }}
        </el-form-item>
<!--        <el-form-item label="车费" prop="travel_mode_fee">-->
<!--          {{ currentRow.travel_mode_fee }}-->
<!--        </el-form-item>-->
        <el-form-item label="订单状态" prop="travel_mode_fee">
          <el-tag :type="currentRow.statusText2.color" >{{ currentRow.statusText2.value }}</el-tag>
        </el-form-item>
        <el-form-item label="退款金额" prop="back_amount">
          <el-radio-group v-model="currentRow.statusText2.value" @change="changeBackAmount">
<!--            <el-radio-button label="待接单">项目+车费</el-radio-button>-->
            <el-radio-button label="已接单">项目费</el-radio-button>
            <el-radio-button label="已到达">项目费一半</el-radio-button>
          </el-radio-group>
          <el-input style="margin-top: 20px" v-model="currentRow.back_amount" type="number">
          </el-input>
        </el-form-item>
        <el-form-item label="退款结果" prop="back_result">
          <el-input type="textarea" v-model="currentRow.back_result"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogValue = false">取消</el-button>
          <el-button type="primary" @click="confirmDialog">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配阿姨对话框 -->
    <el-dialog v-model="assignDialogVisible" title="分配阿姨" width="500px">
      <el-form ref="assignFormRef" :model="assignForm" :rules="assignRules">
        <el-form-item label="选择阿姨" prop="staff_id">
          <el-select style="width: 100%" filterable v-model="assignForm.staff_id">
            <el-option
              v-for="item in staffList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssign">
            确认分配
          </el-button>
        </div>
      </template>
    </el-dialog>

  </PageMain>
</template>
<script setup>
import useTable from "@/utils/useTable";
import {http} from "@/api";
import {ref} from "vue";
import {useRoute} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute()
const memberList = ref([])
const staffList = ref([])
http.Member.list().then(res => {
  memberList.value = res.data
})
http.Staff.list({
  is_all: 1
}).then(res => {
  staffList.value = res.data
})
/**
 * 定时任务
 */
const task = ref(null)
const setTask = () => {
  clearInterval(task.value)
  task.value = setInterval(() => {
    dataSource.value.forEach(item => {
      if (item.serve_time && !item.serve_end_time) {
        // 项目总时长分钟
        let total = item.orderDetails.reduce((prev, next) => {
          return prev + next.good.duration * next.count;
        }, 0);
        // 服务开始时间 serve_time，服务时长 total 距离当前时间还剩余多少
        const serve_time = new Date(item.serve_time).getTime()
        const end_time = serve_time + total * 60 * 1000
        // 计算当前时间距离结束时间还剩余多少分多少秒
        const now = new Date().getTime()
        const diff = end_time - now
        // 计算分、秒
        const minute = Math.floor(diff / 1000 / 60)
        const second = Math.floor(diff / 1000 % 60)
        item.end_serve_time = `${minute}分${second}秒`
      }
      if (item.serve_time && item.serve_end_time) {
        // 服务开始时间 serve_time，服务时长 total 距离当前时间还剩余多少
        const serve_time = new Date(item.serve_time).getTime()
        const end_time = new Date(item.serve_end_time).getTime()
        const diff = end_time - serve_time
        // 计算分、秒
        const minute = Math.floor(diff / 1000 / 60)
        const second = Math.floor(diff / 1000 % 60)
        item.end_serve_time = `${minute}分${second}秒`
      }
    })
  }, 1000)
}
/**
 * 表格
 * @type {Ref<UnwrapRef<*[]>>}
 */
const {
  searchParams,
  pageNo,
  pageSize,
  total,
  changePage,
  changeSize,
  dataSource,
  search,
  reset,
  openAdd,
  openEdit,
  openDelete
} = useTable({
  requestFn: http.ProductOrder,
  routerPre: 'ProductOrder',
  format: (data) => {
    setTask()
    return data.map(item => {
      if (item.address) {
        item.address = JSON.parse(item.address) || {}
      }
      if (item.serve_time === 'Invalid Date') {
        item.serve_time = ''
      }
      item.statusText = {
        color: '',
        value: '',
      }
      // 设置状态
      if (item.pay_status === 0) {
        if (item.order_status === 0) {
          item.statusText = {
            color: 'orange',
            value: '待支付',
          }
        } else if (item.order_status === -1) {
          item.statusText = {
            color: 'grey',
            value: '已取消',
          }
        }
      } else if (item.pay_status === 1) {
        if (item.order_status === 0) {
          item.statusText = {
            color: 'warning',
            value: '待接单',
          }
        } else if (item.order_status === 1) {
          item.statusText = {
            color: 'warning',
            value: '已接单',
          }
        } else if (item.order_status === 2) {
          item.statusText = {
            color: 'primary',
            value: '已到达',
          }
        } else if (item.order_status === 3) {
          item.statusText = {
            color: 'primary',
            value: '服务中',
          }
        } else if (item.order_status === 4) {
          item.statusText = {
            color: 'success',
            value: '已完成',
          }
        } else if (item.order_status === -1) {
          item.statusText = {
            color: 'info',
            value: '已取消',
          }
        }
      } else if (item.pay_status === 2) {
        item.statusText = {
          color: 'error',
          value: '待退款',
        }
      } else if (item.pay_status === 3) {
        item.statusText = {
          color: 'error',
          value: '退款中',
        }
      } else if (item.pay_status === 4) {
        item.statusText = {
          color: 'green',
          value: '退款成功',
        }
      } else if (item.pay_status === 5) {
        item.statusText = {
          color: 'green',
          value: '取消退款',
        }
      }

      if (item.order_status === 0) {
        item.statusText2 = {
          color: 'warning',
          value: '待接单',
        }
      } else if (item.order_status === 1) {
        item.statusText2 = {
          color: 'warning',
          value: '已接单',
        }
      } else if (item.order_status === 2) {
        item.statusText2 = {
          color: 'primary',
          value: '已到达',
        }
      } else if (item.order_status === 3) {
        item.statusText2 = {
          color: 'primary',
          value: '服务中',
        }
      } else if (item.order_status === 4) {
        item.statusText2 = {
          color: 'success',
          value: '已完成',
        }
      } else if (item.order_status === -1) {
        item.statusText2 = {
          color: 'info',
          value: '已取消',
        }
      }
      return {
        ...item,
      }
    })
  },
  params: {
    staff_id: route.query.staff_id,
    member_id: route.query.member_id,
    start_time: '',
    end_time: '',
    order_no: '',
    status: 'all'
  }
})
const handleClick = (tab, event) => {
  search()
}


const dialogValue = ref(false)
const currentRow = ref({})
const rules = ref({
  back_amount: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  back_result: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
})
const openDialog = (row) => {
  currentRow.value = {
    ...row,
    back_amount: 0,
    back_result: '同意'
  }
  changeBackAmount(currentRow.value.statusText2.value)
  dialogValue.value = true
}
const formRef = ref(null)
const changeBackAmount = (e) => {
  if (currentRow.value.pay_amount === 0) {
    currentRow.value.back_amount = 0
    return
  }
  console.log(e)
  if (e === '待接单') {
    currentRow.value.back_amount = currentRow.value.pay_amount
  } else if (e === '已接单') {
    currentRow.value.back_amount = currentRow.value.pay_amount - currentRow.value.travel_mode_fee
  } else if (e === '已到达') {
    currentRow.value.back_amount = (currentRow.value.pay_amount - currentRow.value.travel_mode_fee) / 2
  }
}
const confirmDialog = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (currentRow.value.pay_amount < currentRow.back_amount) {
        ElMessage.error('退款金额不能大于实付金额')
        return
      }
      http.ProductOrder.refund({
        id: currentRow.value.id,
        back_amount: currentRow.value.back_amount,
        back_result: currentRow.value.back_result
      }).then(() => {
        dialogValue.value = false
        search()
      })
    }
  })
}
const openDialog2 = (row) => {
  ElMessageBox.confirm(
      '是否确认取消？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        http.ProductOrder.update({
          id: row.id,
          pay_status: 5
        }).then(res => {
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          search()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '操作取消',
        })
      })
}

const assignDialogVisible = ref(false)
const assignForm = ref({
  id: null,
  staff_id: null
})
const assignRules = ref({
  staff_id: [
    { required: true, message: '请选择阿姨', trigger: 'change' },
  ],
})
const assignFormRef = ref(null)

const openAssignDialog = (row) => {
  assignForm.value = {
    id: row.id,
    staff_id: null
  }
  assignDialogVisible.value = true
}

const confirmAssign = () => {
  assignFormRef.value.validate((valid) => {
    if (valid) {
      http.ProductOrder.update({
        id: assignForm.value.id,
        staff_id: assignForm.value.staff_id,
        order_status: 2
      }).then(() => {
        ElMessage.success('分配成功')
        assignDialogVisible.value = false
        search()
      })
    }
  })
}
</script>

<style scoped lang="scss">

</style>
